/*
 * Copyright 2011-2025 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0.
 * See `LICENSE` in the project root for license information.
 */

package me.ijleex.platform.core.util;

import java.nio.ByteBuffer;

/**
 * {@code byte[]}与{@code int}转换处理工具.
 *
 * @author liym
 * @since 2024-09-02 21:49 新建
 */
public final class ByteUtils {

    // https://www.cnblogs.com/dazhu123/p/12558035.html

    private ByteUtils() {
        throw new IllegalAccessError("Utility class");
    }

    /**
     * 将{@code int}转换为{@code byte[]}，由高位到低位
     *
     * @param x 需要转换为byte数组的数值
     * @return {@code byte[]}
     * @see ByteBuffer#allocate(int)
     * @see ByteBuffer#putInt(int, int)
     */
    public static byte[] intToBytes(int x) {
        byte[] result = new byte[4];
        result[0] = (byte) ((x >> 8 * 3) & 0xFF);
        result[1] = (byte) ((x >> 8 * 2) & 0xFF);
        result[2] = (byte) ((x >> 8) & 0xFF);
        result[3] = (byte) (x & 0xFF);
        return result;
    }

    /**
     * 将{@code byte[]}转换为{@code int}
     *
     * @param bytes 需要转换成int的数组
     * @return {@code int}
     * @see ByteBuffer#wrap(byte[])
     * @see ByteBuffer#getInt()
     */
    public static int bytesToInt(byte[] bytes) {
        int result = 0;
        for (int i = 0; i < 4; i++) {
            int shift = (3 - i) * 8;
            result += (bytes[i] & 0xFF) << shift;
        }
        return result;
    }

    /**
     * 将{@code long}转换为{@code byte[]}
     *
     * @param x 需要转换为byte数组的数值
     * @return {@code byte[]}
     * @since 2025-02-12 21:08
     */
    public static byte[] longToBytes(long x) {
        final ByteBuffer buf = ByteBuffer.allocate(Long.BYTES);
        buf.putLong(0, x);
        return buf.array();
    }

    /**
     * 将{@code byte[]}转换为{@code long}
     *
     * @param bytes 需要转换成long的数组
     * @return {@code long}
     * @since 2025-02-12 21:08
     */
    public static long bytesToLong(byte[] bytes) {
        final ByteBuffer buf = ByteBuffer.wrap(bytes);
        return buf.getLong();
    }

}
